<template>
    <view class="bg-content">
        <div style="background-color: white; padding: 15px;">
            <u-form ref="validateFormRef" :model="validateForm.value" :label-width="200">
                <u-form-item label="商城图片" prop="sysFileId" required>
                    <u-upload ref="uUpload" :multiple="false" :auto-upload="false" :max-count="1" :show-progress="false" :file-list="fileList"
                              @on-remove="onRemove($event)" @on-choose-complete="onChooseComplete($event)"></u-upload>
                </u-form-item>
                <u-form-item label="省市区" prop="region" required>
                    <u-input type="select" :select-open="pickerShow" v-model="validateForm.value.region" placeholder="省市区县、乡镇等" @click="pickerShow = true"/>
                </u-form-item>
                <u-form-item label="名称" prop="name" required>
                    <u-input v-model="validateForm.value.name" placeholder="请输入名称"/>
                </u-form-item>
                <u-form-item label="标题" prop="title">
                    <u-input v-model="validateForm.value.title" placeholder="请输入标题"/>
                </u-form-item>
                <u-form-item label="副标题" prop="subTitle">
                    <u-input v-model="validateForm.value.subTitle" placeholder="请输入副标题"/>
                </u-form-item>
                <u-form-item label="简介" prop="introduction">
                    <u-input type="textarea" height="40" v-model="validateForm.value.introduction" placeholder="请输入简介"/>
                </u-form-item>
                <u-form-item label="联系电话" prop="phone" required>
                    <u-input v-model="validateForm.value.phone" placeholder="请输入联系电话"/>
                </u-form-item>
                <u-form-item label="邮箱" prop="email" required>
                    <u-input v-model="validateForm.value.email" placeholder="请输入邮箱"/>
                </u-form-item>
                <u-form-item label="验证码" prop="identifyingCode" required>
                    <u-input placeholder="请输入验证码" v-model="validateForm.value.identifyingCode" type="text"></u-input>
                    <u-button slot="right" type="success" size="mini" @click="getCode">{{codeTips}}</u-button>
                </u-form-item>
                <u-form-item label="应用推广粉丝收益比例" :label-width="350" prop="expandEarningsRate" required>
                    <u-input v-model="validateForm.value.expandEarningsRate" placeholder="请输入应用推广粉丝收益比例"/>
                </u-form-item>
                <u-form-item label="应用推广粉丝的粉丝收益比例" :label-width="400" prop="thirdEarningsRate" required>
                    <u-input v-model="validateForm.value.thirdEarningsRate" placeholder="请输入应用推广粉丝的粉丝收益比例"/>
                </u-form-item>
                <u-form-item label="商城类型" prop="type" required>
                    <u-input type="select" :select-open="validateForm.controls.type.isShow" v-model="validateForm.controls.type.textDesc"
                             placeholder="请选择商城类型" @click="validateForm.controls.type.isShow = true; $forceUpdate();"></u-input>
                </u-form-item>
                <u-form-item label="是否开放开店功能" :label-width="350" prop="isOpenStore" required>
                    <u-input type="select" :select-open="validateForm.controls.isOpenStore.isShow" v-model="validateForm.controls.isOpenStore.textDesc"
                             placeholder="请选择是否开放开店功能" @click="validateForm.controls.isOpenStore.isShow = true; $forceUpdate();"></u-input>
                </u-form-item>
                <u-form-item label="是否开放参与商城功能" :label-width="350" prop="isOpenCommunity" required>
                    <u-input type="select" :select-open="validateForm.controls.isOpenCommunity.isShow" v-model="validateForm.controls.isOpenCommunity.textDesc"
                             placeholder="请选择是否开放参与商城功能" @click="validateForm.controls.isOpenCommunity.isShow = true; $forceUpdate();"></u-input>
                </u-form-item>
                <u-form-item label="状态" prop="status" required>
                    <u-input type="select" :select-open="validateForm.controls.status.isShow" v-model="validateForm.controls.status.textDesc"
                             placeholder="请选择状态" @click="validateForm.controls.status.isShow = true; $forceUpdate();"></u-input>
                </u-form-item>
                <u-form-item label="底部导航栏显示风格" label-position="top" prop="tabbarType" required>
                    <!--<u-input v-model="validateForm.value.logisticsCompanyName" type="select" placeholder="请选择快递公司" right-icon="arrow-right"-->
                    <!--@click="navigateTo(`/pages/common/logistics-company-select/index`, null, validateForm.value)"/>-->
                    <u-cell-item
                            @click="navigateTo(`/pages/sub/sub3-community-platform/community-platform/community-platform-community/community-platform-community-tabbar-select/index`, null, validateForm.value)">
                        <div slot="icon">
                            <image style="height: 45px;" :src="`/pages/sub/sub3-community-platform/static/img/tabbar/tabbar${validateForm.value.tabbarType}.jpg`"></image>
                        </div>
                    </u-cell-item>
                </u-form-item>
            </u-form>

            <u-button type="error" @click="submit">提交</u-button>
        </div>

        <div class="table table-bordered" style="margin-top: 10px; background: white;">
            <div class="tr">
                <div class="td" style="width: 100px;">
                    商城类型说明
                </div>
                <div class="td">
                    <div>
                        1.公共商城：平台商品是否可以接入该商城进行售卖，引用平台商品分类+自定义商品分类。
                    </div>
                    <div>
                        2.封闭商城（自定义）：平台商品无法接入该商城，自定义商品分类。
                    </div>
                    <div>
                        3.公司&业务员模式、公司&客户模式、公司&业务员模式&客户模式：自定义商品分类、只有商城管理员可售卖商品。
                    </div>
                </div>
            </div>
            <div class="tr">
                <div class="td" style="width: 100px;">
                    应用推广粉丝收益比例说明
                </div>
                <div class="td">
                    如果商城用户A是通过某用户或店铺B推广加入的，则用户A在该商城的消费将会给B带来一定比例的收入，<label style="color: red;">例如：比例为0.005则将用户A消费金额提取千分之五作为B的推广收益。</label>
                </div>
            </div>
            <div class="tr">
                <div class="td" style="width: 100px;">
                    应用推广粉丝的粉丝收益比例说明
                </div>
                <div class="td">
                    如果商城用户A是通过某用户或店铺B推广加入的，C用户是A用户推广加入。则用户C在该商城的消费将会给A带来一定比例的收入，B也会产生一定的收益，
                    <label style="color: red;">例如：比例为0.002则将用户C消费金额提取千分之二作为B的推广收益。（A用户的推广收益是0.005，所以将会提取C用户消费金额的0.005+0.002作为A用户和B用户的推广收益）</label>
                </div>
            </div>
            <div class="tr">
                <div class="td" style="width: 100px;">
                    是否开放开店功能说明
                </div>
                <div class="td">
                    除了商城管理员可以开店销售商品外，其他普通用户是否可以开店销售用户（仅对商城类型为：公共商城，封闭商城（自定义）有效。商城类型为：公司&业务员模式，公司&客户模式，公司&业务员模式&客户模式只有商城管理员可以开店。）。
                </div>
            </div>
            <div class="tr">
                <div class="td" style="width: 100px;">
                    是否开放参与商城功能说明
                </div>
                <div class="td">
                    除了商城管理员外，其他用户是否有权利发布商城动态等信息。
                </div>
            </div>
        </div>

        <u-picker mode="region" v-model="pickerShow" @confirm="regionConfirm" v-if="!validateForm.value.provinceName"></u-picker>
        <u-picker mode="region" v-model="pickerShow" @confirm="regionConfirm" v-if="validateForm.value.provinceName"
                  :default-region="[validateForm.value.provinceName, validateForm.value.cityName, validateForm.value.areaName]"></u-picker>

        <!--邮箱验证码-->
        <u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.type.isShow" :list="validateForm.controls.type.options"
                  :default-value="validateForm.controls.type.defaultValue"
                  @cancel="validateForm.controls.type.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.type)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.isOpenStore.isShow" :list="validateForm.controls.isOpenStore.options"
                  :default-value="validateForm.controls.isOpenStore.defaultValue"
                  @cancel="validateForm.controls.isOpenStore.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.isOpenStore)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.isOpenCommunity.isShow" :list="validateForm.controls.isOpenCommunity.options"
                  :default-value="validateForm.controls.isOpenCommunity.defaultValue"
                  @cancel="validateForm.controls.isOpenCommunity.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.isOpenCommunity)"></u-select>

        <u-select mode="single-column" label-name="name" value-name="code" :mask-close-able="false"
                  v-model="validateForm.controls.status.isShow" :list="validateForm.controls.status.options"
                  :default-value="validateForm.controls.status.defaultValue"
                  @cancel="validateForm.controls.status.isShow = false; $forceUpdate();"
                  @confirm="UFormUtil.selectSingleColumnConfirm($event, validateForm.controls.status)"></u-select>
    </view>
</template>

<script>

    import {CommonService} from "@/dev/services/common.service";
    import {TbEmailIdentifyingCodeService} from "@/dev/services/tb_email_identifying_code.service";
    import {UFormUtil} from "@/dev/core/utils/u-form.util";
    import {SysFileService} from "@/dev/services/sys-file.service";
    import {SysDictionaryService} from "@/dev/services/sys-dictionary.service";
    import {QiniuCloudUtil} from "@/dev/core/utils/qiniu-cloud.util";
    import {CommonUtil} from "@/dev/core/utils/common.util";
    import {TbCommunityService} from "@/dev/services/tb-community.service";
    import {LocalStorageUtil} from "@/dev/core/utils/local-storage.util";

    export default {
        data() {
            return {
                fileList: [],
                pickerShow: false,
                codeTips: '',  // 获取验证码提示语
                validateForm: {
                    value: {
                        id: null,
                        sysFileId: '',  // 图片sysFile.id
                        region: '',
                        provinceName: '',
                        cityName: '',
                        areaName: '',
                        name: '',
                        title: '',
                        subTitle: '',
                        introduction: '',
                        address: '',
                        phone: '',
                        email: '',
                        type: '',
                        identifyingCode: '',
                        expandEarningsRate: '0',
                        thirdEarningsRate: '0',
                        isOpenStore: "0",
                        isOpenCommunity: "0",
                        status: '1',
                        tabbarType: '0'
                    },
                    rules: {
                        sysFileId: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        region: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        name: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new CommonService().uniqueCheckByFields({
                                        "tableName": "tb_community",
                                        "fieldList": [
                                            {"fieldName": "province_name", "fieldValue": this.validateForm.value.provinceName},
                                            {"fieldName": "city_name", "fieldValue": this.validateForm.value.cityName},
                                            {"fieldName": "area_name", "fieldValue": this.validateForm.value.areaName},
                                            {"fieldName": "name", "fieldValue": this.validateForm.value.name}
                                        ],
                                        "excludeId": this.validateForm.value.id
                                    }).then(result => {
                                        if (result.status === "fail") {
                                            callback(new Error('输入的内容已存在！'));
                                        } else {
                                            callback()
                                        }
                                    });
                                }
                            }
                        ],
                        address: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        phone: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^1[0-9]{10}$/, message: '请输入有效的手机号码!', trigger: ['change', 'blur']}
                        ],
                        email: [
                            {required: true, type: "email", message: '请输入有效的邮箱号码', trigger: ['change', 'blur']},
                        ],
                        identifyingCode: [
                            {required: true, message: '请输入邮箱验证码', trigger: ['change', 'blur']},
                            {
                                trigger: ['blur'],
                                asyncValidator: (rule, value, callback) => {
                                    new TbEmailIdentifyingCodeService().mailIdentifyingCodeCheck(this.validateForm.value.email, this.validateForm.value.identifyingCode).then(result => {
                                        if (result.status === "success") {
                                            callback()
                                        } else {
                                            callback(new Error(result.message));
                                        }
                                    });
                                }
                            }
                        ],
                        type: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        expandEarningsRate: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^0(.[0-9]{1,3})?$/, message: '请输入请输入大于或等于0且小于1，最多有三位小数的数值!!', trigger: ['change', 'blur']}
                        ],
                        thirdEarningsRate: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^0(.[0-9]{1,3})?$/, message: '请输入请输入大于或等于0且小于1，最多有三位小数的数值!', trigger: ['change', 'blur']}
                        ],
                        isOpenStore: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                        isOpenCommunity: [
                            {required: true, message: '必填项!', trigger: ['change', 'blur']},
                            {pattern: /^(?=.*\S).+$/, message: '必填项!', trigger: ['change', 'blur']}
                        ],
                    }
                }
            }
        },
        onReady() {
            const _self = this;
            this.validateForm.value.region = this.objParams.provinceName + '-' + this.objParams.cityName + '-' + this.objParams.areaName;
            UFormUtil.setDefaultValues(this.validateForm, this.objParams);

            new SysFileService().findQiniuCloudImageUrl({
                fkId: this.objParams.id,
                type: 'image/jpeg',
            }).then(result => {
                if (result.url) {
                    _self.validateForm.value.sysFileId = result.id;
                    _self.fileList.push({
                        id: result.id,
                        url: result.url + "?_timestamp=" + new Date().getTime(),
                    });
                }
                _self.$forceUpdate()
            });

            new SysDictionaryService().optionList('tb_community@type', null).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.type, result);
                _self.$forceUpdate();
            });

            UFormUtil.setOptions(_self.validateForm.controls.isOpenStore, [{name: '否', code: '0'}, {name: '是', code: '1'}]);
            UFormUtil.setOptions(_self.validateForm.controls.isOpenCommunity, [{name: '否', code: '0'}, {name: '是', code: '1'}]);

            new SysDictionaryService().optionList('status', null).then(result => {
                UFormUtil.setOptions(_self.validateForm.controls.status, result);
                _self.$forceUpdate();
            });

            _self.$forceUpdate();
        },
        methods: {
            // 选择地区回调
            regionConfirm(e) {
                this.validateForm.value.region = e.province.label + '-' + e.city.label + '-' + e.area.label;
                this.validateForm.value.provinceName = e.province.label;
                this.validateForm.value.cityName = e.city.label;
                this.validateForm.value.areaName = e.area.label;
            },
            codeChange(text) {
                this.codeTips = text;
            },
            // 获取验证码
            getCode() {
                const _self = this;
                if (this.$refs.uCode.canGetCode) {
                    // 模拟向后端请求验证码
                    uni.showLoading({
                        title: '正在获取验证码',
                        mask: true
                    });

                    this.validateForm.value.email = CommonUtil.trim(this.validateForm.value.email);
                    if (!this.validateForm.value.email) {
                        this.$u.toast('请先输入邮箱');
                        return;
                    }

                    new TbEmailIdentifyingCodeService().sendMailIdentifyingCode(this.validateForm.value.email).then(result => {
                        CommonUtil.alert(result.message);
                        uni.hideLoading();
                        // 通知验证码组件内部开始倒计时
                        _self.$refs.uCode.start();
                    });
                } else {
                    this.$u.toast('倒计时结束后再发送');
                }
            },
            onRemove($event) {
                console.log($event);
                const _self = this;
                new SysFileService().deleteSysFile({
                    id: _self.validateForm.value.sysFileId
                }).then(result => {
                    _self.validateForm.value.sysFileId = '';
                    UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
                    CommonUtil.toast("图片删除成功");
                    _self.$forceUpdate()
                });
            },
            onChooseComplete($event) {
                console.log($event);
                const _self = this;
                QiniuCloudUtil.uploadToCloud(_self.validateForm.value.id, $event[0].file.path).then(result => {
                    if (result.status === "success") {
                        _self.validateForm.value.sysFileId = result.id;
                        CommonUtil.toast(result.message);
                    } else {
                        CommonUtil.alert(result.message);
                    }
                    UFormUtil.validation(_self.$refs.validateFormRef, 'sysFileId');
                });
            },
            submit() {
                const _self = this;
                this.$refs.validateFormRef.validate(valid => {
                    if (valid) {
                        console.log('验证通过', _self.validateForm.value);
                        CommonUtil.alert({
                            title: '提示！',
                            content: '确认提交吗？',
                            showCancel: true, // 是否显示取消按钮
                            success: function (res) {
                                if (res.cancel) { // 点击取消,默认隐藏弹框
                                } else { // 点击确定
                                    new TbCommunityService().updateTbCommunity(_self.validateForm.value).then(result => {
                                        Object.assign(_self.globalVariable.userInfo.tbCommunity, CommonUtil.deleteNullAttrInObject(result));

                                        _self.globalVariable.userInfo.tbCommunityUserList.forEach(item => {
                                            if (item.tbCommunity.id === result.id) {
                                                Object.assign(item.tbCommunity, CommonUtil.deleteNullAttrInObject(result));
                                            }
                                        });

                                        LocalStorageUtil.setItem("userInfo", _self.globalVariable.userInfo);
                                        CommonUtil.toastNavigateBack('更新成功')
                                    });
                                }
                            }
                        });
                    } else {
                        console.log('验证失败');
                    }
                });
            }
        }
    }
</script>

<style lang="scss" scoped>
</style>
